(function (window) {
    var ENV_CONFIG = {
        dev: 'dev',
        prod: 'prod'
    }
    var ENV = ENV_CONFIG.prod
    // 菜单配置
    // 测试环境
    var menuConfig
    if (ENV === ENV_CONFIG.dev) {
        menuConfig = {
            '012M000000019vi': ['商城咨询', '产品查询', '零件号查询', '订单查询', '售后服务', '商务合作'],
            '012M000000019vn': ['投诉建议'],
        }
    } else if (ENV === ENV_CONFIG.prod) {
        // 生产环境
        menuConfig = {
            '0123s000000aLwJ': ['商城咨询', '产品查询', '零件号查询', '订单查询', '售后服务', '商务合作'],
            '0123s000000aLwI': ['投诉建议'],
        }
    }


    var url = decodeURIComponent(window.location.href)
    // 路径参数
    var urlQueryTypes = ['userName', 'realName', 'phone', 'roleName', 'WWID', 'enterpriseName', 'menu']

    // 调用app端返回
    var notificationApp = {
        backToApp: function () {
            notificationAppFunc('BackToApp', '')
        },
        loadingSuccess: function () {
            notificationAppFunc('loadingSuccess', '');
        },
        loadingError: function () {
            notificationAppFunc('loadingError', '');
        }
    }
    var timeOut = 40 * 1000
    // 加载超时报错
    var timeClear
    // 系统初始化
    init()

    function openWindow(urlQuery) {
        if (!urlQuery) {
            // 获取浏览器参数
            urlQuery = getParams(urlQueryTypes, url)
            // 获取menu对应的caseRecordType
            urlQuery.caseRecordType = getCaseRecordTypeByMenu(urlQuery.menu, menuConfig)
        }
        timeClear = setTimeout(function () {
            notificationApp.loadingError()
        }, timeOut)
        initESWSetting(urlQuery)
        window.embedded_svc.onHelpButtonClick()
    }

    function init() {
        // 获取浏览器参数
        var urlQuery = getParams(urlQueryTypes, url)
        // 获取menu对应的caseRecordType
        urlQuery.caseRecordType = getCaseRecordTypeByMenu(urlQuery.menu, menuConfig)
        initHanlerLoadingSuccess(embedded_svc, notificationApp.loadingSuccess)
        // 监听关闭聊天窗口按钮触发
        initHanlerClose(embedded_svc, notificationApp.backToApp)
        // 初始化setting参数
        initESWSetting(urlQuery)
        // 初始化在线客服
        initESW('https://service.force.com')
        // 自动填充离线消息
        initOfflineMessage(urlQuery)
        webScrollOnForce()
        // webScrollOnForce2()
        // 将open绑定至window供app端调用
        window.openWindow = openWindow
        window.onload = function () {
            openWindow()
        }
    }

    // 初始化ESW
    function initESW(gslbBaseURL) {
        if (ENV === ENV_CONFIG.dev) {
            // 测试环境
            embedded_svc.init(
                'https://cummins-cn--sccs.my.salesforce.com',
                'https://sccs-wosmsapi.cs7.force.com/',
                gslbBaseURL,
                '00DM0000000GBdB',
                'Supply_Chain_Mobile_Parts_Chat_Service',
                {
                    baseLiveAgentContentURL: 'https://c.la3-c1cs-dfw.salesforceliveagent.com/content',
                    deploymentId: '572M000000000cA',
                    buttonId: '573M000000000YX',
                    baseLiveAgentURL: 'https://d.la3-c1cs-dfw.salesforceliveagent.com/chat',
                    eswLiveAgentDevName: 'EmbeddedServiceLiveAgent_Parent04IM0000000007lMAA_1710ced3801',
                    isOfflineSupportEnabled: true
                }
            );
        } else if (ENV === ENV_CONFIG.prod) {
            // 生产环境
            embedded_svc.init(
                'https://cummins-cn.my.salesforce.com',
                'https://wosmsapi.secure.force.com',
                gslbBaseURL,
                '00D6A000000t764',
                'Supply_Chain_Mobile_Parts_Chat_Service',
                {
                    baseLiveAgentContentURL: 'https://c.la4-c2-ia2.salesforceliveagent.com/content',
                    deploymentId: '5723s000000lOJs',
                    buttonId: '5733s000000lAj5',
                    baseLiveAgentURL: 'https://d.la4-c2-ia2.salesforceliveagent.com/chat',
                    eswLiveAgentDevName: 'EmbeddedServiceLiveAgent_Parent04I3s0000004F2YEAU_171b1e278db',
                    isOfflineSupportEnabled: true
                })
        }
    }

    function initESWSetting(options) {
        embedded_svc.settings.displayHelpButton = false; //Or false
        embedded_svc.settings.autoOpenPostChat = true; //Or false
        embedded_svc.settings.enabledFeatures = ['LiveAgent'];
        embedded_svc.settings.entryFeature = 'LiveAgent';
        embedded_svc.settings.language = 'zh-CN'; //For example, enter 'en' or 'en-US'
        embedded_svc.settings.defaultMinimizedText = '在线客服'; //(Defaults to Chat with an Expert)
        embedded_svc.settings.offlineSupportMinimizedText = '离线留言'; //(Defaults to Contact Us)
        embedded_svc.settings.loadingText = '连接中'; //(Defaults to Loading)

        //get the param value from the URL setting, this is only for test
        embedded_svc.settings.extraPrechatFormDetails = [
            {
                label: '姓名',
                value: options.realName,
                displayToAgent: true,
                transcriptFields: ['Vistor_Name__c']
            },
            {
                label: '登录用户名',
                value: options.userName,
                displayToAgent: true,
                transcriptFields: ['Vistor_LoginUN__c']
            },
            {
                label: '电话',
                value: options.phone,
                displayToAgent: true,
                transcriptFields: ['Vistor_Phone__c']
            },
            {
                label: '所属企业',
                value: options.enterpriseName,
                displayToAgent: true,
                transcriptFields: ['Vistor_Company__c']
            },
            {
                label: '角色',
                value: options.roleName,
                displayToAgent: true,
                transcriptFields: ['Vistor_Role__c']
            },
            {
                label: 'WWID',
                value: options.WWID,
                displayToAgent: true,
                transcriptFields: ['Vistor_WWID__c']
            },
            {
                label: '点击菜单',
                value: options.menu,
                displayToAgent: true,
                transcriptFields: ['Menu__c']
            },
            {
                label: 'caseRecordType',
                value: options.caseRecordType,
                displayToAgent: false
            },
            {
                label: 'caseOrigin',
                value: '12',
                displayToAgent: false
            }
        ];//Send the agent more information and add information to the chat transcript
        embedded_svc.settings.extraPrechatInfo = [
            {
                entityFieldMaps: [{
                    doCreate: false,
                    doFind: true,
                    fieldName: 'MobilePhone',
                    isExactMatch: true,
                    label: '电话'
                }],
                entityName: 'Contact',
                saveToTranscript: 'ContactId',
                linkToEntityName: 'Case',
                linkToEntityField: 'ContactId',
                showOnCreate: true
            },
            {
                entityFieldMaps: [
                    {
                        doCreate: true,
                        doFind: false,
                        fieldName: 'RecordTypeId',
                        isExactMatch: true,
                        label: 'caseRecordType'
                    },
                    {
                        doCreate: true,
                        doFind: false,
                        fieldName: 'Origin',
                        isExactMatch: true,
                        label: 'caseOrigin'
                    },
                    {
                        doCreate: true,
                        doFind: false,
                        fieldName: 'SC_Category_Second__c',
                        isExactMatch: true,
                        label: '点击菜单'
                    }
                ],
                entityName: 'Case',
                saveToTranscript: 'CaseId',
                showOnCreate: true
            }
        ];
        // Settings for Chat
        embedded_svc.settings.directToButtonRouting = function (prechatFormData) {
            // Dynamically changes the button ID based on what the visitor enters in the pre-chat form.
            if (ENV === ENV_CONFIG.dev) {
                // 测试环境
                if (options.menu === '投诉建议') {
                    return '573M00000008OhP';//complaint button id from salesforce as this button do not use the default value
                }
                if (options.menu === '零件号查询') {
                    return '573M00000008Ohe';
                }
            } else if (ENV === ENV_CONFIG.prod) {
                // 生产环境
                if (options.menu === '投诉建议') {
                    return '5733s000000lAjA';//complaint button id from salesforce as this button do not use the default value
                }
                if (options.menu === '零件号查询') {
                    return '5733s000000lAjF';
                }
            }
        };
    }

    // 初始化离线消息
    function initOfflineMessage(options) {
//set the offline support form value
        let _XMLHttpRequest = XMLHttpRequest.prototype.open;
        XMLHttpRequest.prototype.open = function () {
            this.addEventListener('load', b => {
                let un = document.querySelector('input#SuppliedName');
                if (un != null) {
                    un.value = options.realName;
                    un.dispatchEvent(new Event('change', {'bubbles': !0}));
                }
                let c = document.querySelector('input#SuppliedPhone');
                if (c != null) {
                    c.value = options.phone;
                    c.dispatchEvent(new Event('change', {'bubbles': !0}));
                }
                let d = document.querySelector('select#SC_Category_Second__c');
                if (d != null) {
                    d.value = options.menu;
                    d.dispatchEvent(new Event('change', {'bubbles': !0}));
                }
            });
            _XMLHttpRequest.apply(this, arguments);
        };
    }

    /**
     * 初始化关闭事件
     * hack手段监听聊天窗口关闭事件通知app端
     * @param {Object} embedded_svc
     * @param {function} callback
     * */
    function initHanlerClose(embedded_svc, callback) {
        embedded_svc.addEventHandler("afterDestroy", function (data) {
            try {
                callback();
            } catch (e) {
                console.log('Error-afterDestroy:', e);
            }
        });
    }

    /**
     * 初始化关闭事件
     * hack手段监听聊天窗口关闭事件通知app端
     * @param {Object} embedded_svc
     * @param {function} callback
     * */
    function initHanlerLoadingSuccess(embedded_svc, callback) {
        //override the hideButton function
        embedded_svc.hideHelpButton = function hideHelpButton() {
            try {
                // 关闭错误提示
                clearTimeout(timeClear)
                callback()
            } catch (e) {
                console.log('Error-initHanlerLoadingSuccess:', e);
            }
        };
    }

    function webScrollOnForce() {
        const u = navigator.userAgent
        const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        // 如果是IOS设备
        if (isiOS) {
            let flag = false
            let pageBackNormFunc
            // 聚焦后，键盘弹起
            document.body.addEventListener('focusin', () => {
                flag = true
                pageBackNormFunc && clearTimeout(pageBackNormFunc)
            })
            // 失焦后，键盘关闭
            document.body.addEventListener('focusout', () => {
                if (flag) {
                    // 页面滚动回原来的位置
                    pageBackNormFunc = setTimeout(() => {
                        window.scrollTo({top: 0, left: 0, behavior: 'smooth'})
                    }, 200)
                }
                flag = false
            })
        }
    }

    function webScrollOnForce2() {
        const u = navigator.userAgent
        const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
        // 如果是IOS设备
        if (isiOS) {
            window.addEventListener('focusout', function () {
                window.scrollTo(0, 0)
            })
        }
    }

    // 同app端通信
    function notificationAppFunc(func, options) {
        options = options || ''
        var u = navigator.userAgent;
        var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        if (isiOS) {
            window.webkit.messageHandlers[func].postMessage(options);
        } else if (isAndroid) {
            if (typeof window[func] === 'function') {
                window[func](options)
            } else if (typeof window[func].get === 'function') {
                window[func].get(options);
            }
        }
    }

    // utils函数部分
    /**
     * 根据menu获取caseRecordType
     * @param {String} menu 菜单名称
     * @param {Object} menuConfig 菜单配置
     * */
    function getCaseRecordTypeByMenu(menu, menuConfig) {
        var caseRecordType = ''
        Object.keys(menuConfig).forEach(function (id) {
            if (menuConfig[id].indexOf(menu) !== -1) {
                caseRecordType = id
            }
        })
        return caseRecordType
    }

    /**
     * getParam
     * @param  {String} name
     * @param  {String} url   [default:location.href]
     * @return {String|Boolean}
     */
    function getParam(name, url) {
        if (typeof name !== 'string') return false;
        if (!url) url = window.location.href;
        // 当遇到name[xx]时，对方括号做一下转义为 name\[xxx\]，因为下面还需要使用name做正则
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
        var results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }

    /**
     * [getParams 获取多个参数]
     * @param  {Array} names [多个用空格分割]
     * @param  {String} url   [default:location.href]
     * @return {[String|Boolean]}
     */
    function getParams(names, url) {
        var result = {};
        var i = 0,
            len = names.length;
        if (names.length === 0) return false;
        for (; i < len; i++) {
            result[names[i]] = getParam(names[i], url);
        }
        return result;
    }

}(window))
